package com.hikvision.open.app.utils

import android.Manifest
import android.app.Activity
import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.net.Uri
import android.os.Build
import android.provider.Settings
import androidx.appcompat.app.AlertDialog
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentActivity
import com.hikvision.open.app.widget.PermissionDialog

/**
 * 权限管理工具类，用于替代 PermissionX
 */
class PermissionHelper private constructor() {

    companion object {
        const val REQUEST_CODE_STORAGE = 1001
        const val REQUEST_CODE_RECORD_AUDIO = 1002
        const val REQUEST_CODE_CAMERA = 1003
        const val REQUEST_CODE_MULTIPLE = 1004
        const val REQUEST_CODE_SETTINGS = 1005

        /**
         * 检查权限是否已授予
         */
        fun isGranted(context: Context, permission: String): Boolean {
            return ContextCompat.checkSelfPermission(context, permission) == PackageManager.PERMISSION_GRANTED
        }

        /**
         * 请求存储权限
         */
        fun requestStoragePermission(
            activity: FragmentActivity,
            onResult: (Boolean) -> Unit
        ) {
            requestPermission(
                activity,
                Manifest.permission.WRITE_EXTERNAL_STORAGE,
                REQUEST_CODE_STORAGE,
                "正常使用功能，需要您同意开启存储权限。",
                "确定",
                "缺少存储权限，将无法使用功能，请点击“设置”-“权限”打开所需权限。",
                "设置",
                onResult
            )
        }

        /**
         * 请求录音权限
         */
        fun requestRecordAudioPermission(
            activity: FragmentActivity,
            onResult: (Boolean) -> Unit
        ) {
            requestPermission(
                activity,
                Manifest.permission.RECORD_AUDIO,
                REQUEST_CODE_RECORD_AUDIO,
                "正常使用功能，需要您同意开启麦克风权限。",
                "确定",
                "缺少麦克风权限，将无法使用功能，请点击“设置”-“权限”打开所需权限。",
                "设置",
                onResult
            )
        }

        /**
         * 请求摄像头权限
         */
        fun requestCameraPermission(
            activity: FragmentActivity,
            onResult: (Boolean) -> Unit
        ) {
            requestPermission(
                activity,
                Manifest.permission.CAMERA,
                REQUEST_CODE_CAMERA,
                "正常使用功能，需要您同意开启摄像头权限。",
                "确定",
                "缺少摄像头权限，将无法使用功能，请点击“设置”-“权限”打开所需权限。",
                "设置",
                onResult
            )
        }

        /**
         * 请求多个权限
         */
        fun requestMultiplePermissions(
            activity: FragmentActivity,
            permissions: Array<String>,
            reasonMessage: String,
            settingMessage: String,
            onResult: (Map<String, Boolean>) -> Unit
        ) {
            // 检查哪些权限已被授予
            val permissionsToRequest = permissions.filter {
                !isGranted(activity, it)
            }.toTypedArray()

            // 如果所有权限都已授予，直接回调
            if (permissionsToRequest.isEmpty()) {
                val resultMap = permissions.associateWith { true }
                onResult(resultMap)
                return
            }

            // 请求权限
            ActivityCompat.requestPermissions(activity, permissionsToRequest, REQUEST_CODE_MULTIPLE)

            // 存储回调函数
            PermissionResultHandler.addCallback(REQUEST_CODE_MULTIPLE) { grantResults ->
                val resultMap = mutableMapOf<String, Boolean>()
                permissionsToRequest.forEachIndexed { index, permission ->
                    val granted = grantResults.isNotEmpty() && index < grantResults.size &&
                            grantResults[index] == PackageManager.PERMISSION_GRANTED
                    resultMap[permission] = granted
                }
                onResult(resultMap)
            }
        }

        /**
         * 通用权限请求方法
         */
        private fun requestPermission(
            activity: FragmentActivity,
            permission: String,
            requestCode: Int,
            reasonMessage: String,
            positiveText: String,
            settingMessage: String,
            settingText: String,
            onResult: (Boolean) -> Unit
        ) {
            // 如果权限已授予，直接回调
            if (isGranted(activity, permission)) {
                onResult(true)
                return
            }

            // 如果用户之前拒绝过权限，显示解释对话框
            if (ActivityCompat.shouldShowRequestPermissionRationale(activity, permission)) {
                showPermissionDialog(
                    activity,
                    reasonMessage,
                    positiveText,
                    listOf(permission)
                ) { dialog ->
                    dialog.dismiss()
                    ActivityCompat.requestPermissions(activity, arrayOf(permission), requestCode)
                }
            } else {
                // 直接请求权限
                ActivityCompat.requestPermissions(activity, arrayOf(permission), requestCode)
            }

            // 存储回调函数，以便在 onRequestPermissionsResult 中调用
            PermissionResultHandler.addCallback(requestCode) { grantResults ->
                val granted = grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED
                if (granted) {
                    onResult(true)
                } else {
                    // 如果权限被拒绝，显示设置对话框
                    showPermissionDialog(
                        activity,
                        settingMessage,
                        settingText,
                        listOf(permission)
                    ) { dialog ->
                        dialog.dismiss()
                        openAppSettings(activity)
                    }
                    onResult(false)
                }
            }
        }

        /**
         * 显示权限解释对话框
         */
        private fun showPermissionDialog(
            context: Context,
            message: String,
            positiveText: String,
            permissions: List<String>,
            onPositiveClick: (AlertDialog) -> Unit
        ) {
            val dialog = PermissionDialog(
                context,
                message,
                positiveText,
                permissions.toMutableList()
            )
            dialog.show()
            dialog.getPositiveButton().setOnClickListener {
                onPositiveClick(dialog)
            }
        }

        /**
         * 打开应用设置页面
         */
        private fun openAppSettings(activity: Activity) {
            val intent = Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS)
            val uri = Uri.fromParts("package", activity.packageName, null)
            intent.data = uri
            activity.startActivityForResult(intent, REQUEST_CODE_SETTINGS)
        }

        /**
         * 处理权限请求结果
         */
        fun handlePermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray): Boolean {
            return PermissionResultHandler.handlePermissionsResult(requestCode, grantResults)
        }
    }
}